<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/9/19
 * Time: 16:55
 */
namespace App\Service\Admin;

use App\Http\Model\Mysql\BrandModel;
use Carbon\Carbon;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\URL;
use App\Utils\UploadAliOss;

class BrandService extends BaseService
{
    /**
     * 品牌列表页
     * @param array $query  搜索条件
     * @param int $page  当前页码
     * @param int $size  每页数量
     * @return array
     */
    public function brandList(array $query = [], int $page = 1, int $size = 0)
    {
        $where['is_delete'] =   BrandModel::NOT_DELETE;

        /**
         * 搜索店铺ID
         */
        if (isset($query['shop_id']) && !empty($query['shop_id'])) {
            $where['shop_id']   =   (int) $query['shop_id'];
        }

        /**
         * 搜索品牌名称
         */
        if (isset($query['brand_name'])) {
            $where[] =   ['brand_name', 'like', '%' . trim($query['brand_name']) . '%'];
        }

        $size   =   $size <= 0 ? self::PAGE_LIMIT : $size;
        $count  =   BrandModel::with(['shop' => function ($query) {
                        $query->select('id', 'shop_name', 'shop_contact');
                    }])->where($where)->count();

        $list   =   BrandModel::with(['shop' => function ($query) {
                        $query->select('id', 'shop_name', 'shop_contact');
                    }])->where($where)->select(['id', 'shop_id', 'brand_name', 'brand_logo', 'brand_icon', 'brand_desc', 'brand_pic', 'sorting', 'updated_at'])->orderBy('sorting', 'desc')
                    ->limit($size)->offset(($page - 1) * $size)->get()->each(function (&$item) {
                        $item->update_time =   $item->updated_at->toDateTimeString();
                        unset($item->updated_at);
                    });

        if ($list->isEmpty()) {
            return [true, []];
        } else {
            return [true, [
                'count' =>  $count,
                'pages' =>  ceil($count / $size),
                'list'  =>  $list->toArray(),
                'current'=> $page
            ]];
        }
    }

    /**
     * 品牌总列表页
     * @return array
     */
    public function brandTotal()
    {
        $where['is_delete'] =   BrandModel::NOT_DELETE;
        $count  =   BrandModel::with(['shop' => function ($query) {
                        $query->select('id', 'shop_name', 'shop_contact');
                    }])->where($where)->count();

        $list   =   BrandModel::with(['shop' => function ($query) {
                        $query->select('id', 'shop_name', 'shop_contact');
                    }])->where($where)->select(['id', 'shop_id', 'brand_name', 'brand_logo', 'brand_icon', 'brand_desc', 'brand_pic', 'sorting', 'updated_at'])->orderBy('sorting', 'desc')
                        ->get()->each(function (&$item) {
                            $item->update_time =   $item->updated_at->toDateTimeString();
                            unset($item->updated_at);
                        });

        if ($list->isEmpty()) {
            return [true, []];
        } else {
            return [true, [
                'count' =>  $count,
                'pages' =>  1,
                'list'  =>  $list->toArray(),
                'current'=> 1
            ]];
        }
    }

    /**
     * 品牌详情页
     * @param int $brand_id
     * @return array
     */
    public function brandInfo(int $brand_id)
    {
        $brand_info =   BrandModel::where(['id' => $brand_id, 'is_delete' => BrandModel::NOT_DELETE])->select(['id', 'brand_name', 'brand_desc', 'unique_id', 'brand_logo', 'brand_pic', 'brand_icon', 'sorting'])->first();
        if (empty($brand_info)) {
            return [false, '店铺不存在'];
        } else {
            return [true, $brand_info->toArray()];
        }
    }

    /**
     * 品牌添加
     * @param array $params  添加内容
     * @return array
     */
    public function brandAdd(array $params = [])
    {
        $setting_path   =   Config::get('upload.local_path');
        $upload_path    =   public_path($setting_path);
        /**
         * 上传多图到本地
         */
        $logo_name      =   sha1($params['brand_logo']->getClientOriginalName() . createRandomNumber()) . '.' . $params['brand_logo']->extension();
        $pic_name       =   sha1($params['brand_pic']->getClientOriginalName() . createRandomNumber()) . '.' . $params['brand_pic']->extension();
        $icon_name      =   sha1($params['brand_icon']->getClientOriginalName() . createRandomNumber()) . '.' . $params['brand_icon']->extension();

        $params['brand_logo']->move($upload_path, $logo_name);
        $params['brand_pic']->move($upload_path, $pic_name);
        $params['brand_icon']->move($upload_path, $icon_name);

        $upload[$logo_name] =    $upload_path . DIRECTORY_SEPARATOR . $logo_name;
        $upload[$pic_name]  =    $upload_path . DIRECTORY_SEPARATOR . $pic_name;
        $upload[$icon_name] =    $upload_path . DIRECTORY_SEPARATOR . $icon_name;

        /**
         * 上传多图到OSS服务器
         */
        $upload_ali_oss =   new UploadAliOss();
        [$flag, $result]=   $upload_ali_oss->uploadFile($upload);

        if ($flag) {
            /**
             * 删除本地图片
             */
            foreach ($upload as $item) {
                @unlink($item);
            }
        }

        $upload[$logo_name] =    $result[$logo_name] ?? URL::asset($setting_path . '/' . $logo_name);
        $upload[$pic_name]  =    $result[$pic_name] ?? URL::asset($setting_path . '/' . $pic_name);
        $upload[$icon_name] =    $result[$icon_name] ?? URL::asset($setting_path . '/' . $icon_name);

        $insert['shop_id']   =  $params['shop_id'];
        $insert['unique_id'] =  createUniqueID();
        $insert['brand_name']=  $params['brand_name'];
        $insert['sorting']   =  $params['sorting'];
        $insert['brand_desc']=  $params['brand_desc'] ?? '';
        $insert['brand_logo']=  $upload[$logo_name];
        $insert['brand_pic'] =  $upload[$pic_name];
        $insert['brand_icon']=  $upload[$icon_name];

        $insert_result  =   BrandModel::create($insert);
        if ($insert_result) {
            return [true, '添加成功'];
        } else {
            return [false, '添加失败'];
        }
    }

    /**
     * 删除品牌
     * @param int $brand_id     品牌ID
     * @return array
     */
    public function brandDelete(int $brand_id)
    {
        $result =   BrandModel::where(['id' => $brand_id])->update(['is_delete' => BrandModel::IS_DELETE, 'delete_time' => Carbon::now()->timestamp]);
        if ($result) {
            return [true, '删除成功'];
        } else {
            return [false, '删除失败'];
        }
    }

    /**
     * 修改品牌内容
     * @param array $params     修改内容
     * @param int $brand_id     品牌ID
     * @return array
     */
    public function brandEdit(array $params, int $brand_id)
    {
        $update['shop_id']   =  $params['shop_id'];
        $update['brand_name']=  $params['brand_name'];
        $update['sorting']   =  $params['sorting'];
        $update['brand_desc']=  $params['brand_desc'] ?? '';

        $setting_path   =   Config::get('upload.local_path');
        $upload_path    =   public_path($setting_path);

        /**
         * 上传新图片
         */
        if (isset($params['brand_logo'])) {
            $logo_name          =   sha1($params['brand_logo']->getClientOriginalName() . createRandomNumber()) . '.' . $params['brand_logo']->extension();
            $params['brand_logo']->move($upload_path, $logo_name);

            $upload[$logo_name] =    $upload_path . DIRECTORY_SEPARATOR . $logo_name;
        }

        if (isset($params['brand_icon'])) {
            $icon_name           =   sha1($params['brand_icon']->getClientOriginalName() . createRandomNumber()) . '.' . $params['brand_icon']->extension();
            $params['brand_icon']->move($upload_path, $icon_name);

            $upload[$icon_name]  =    $upload_path . DIRECTORY_SEPARATOR . $icon_name;
        }

        if (isset($params['brand_pic'])) {
            $pic_name          =   sha1($params['brand_pic']->getClientOriginalName() . createRandomNumber()) . '.' . $params['brand_pic']->extension();
            $params['brand_pic']->move($upload_path, $pic_name);

            $upload[$pic_name] =    $upload_path . DIRECTORY_SEPARATOR . $pic_name;
        }

        /**
         * 上传多图到OSS服务器
         */
        if (!empty($upload)) {
            $upload_util    =   new UploadAliOss();
            [$flag, $result]=   $upload_util->uploadFile($upload);

            if ($flag) {
                /**
                 * 删除本地图片
                 */
                foreach ($upload as $item) {
                    @unlink($item);
                }
            }

            $update['brand_logo']   =  isset($params['brand_logo']) && isset($result[$logo_name]) ?? URL::asset($setting_path . '/' . $logo_name);
            $update['brand_icon']   =  isset($params['brand_icon']) && isset($result[$icon_name]) ?? URL::asset($setting_path . '/' . $icon_name);
            $update['brand_pic']    =  isset($params['brand_pic']) && isset($result[$pic_name]) ?? URL::asset($setting_path . '/' . $pic_name);
        }

        $update_result  =   BrandModel::where(['id' => $brand_id])->update($update);
        if ($update_result) {
            return [true, '修改成功'];
        }

        return [false, '修改失败'];
    }

}

